﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyRead.API.Appicant.Command;
using B.S.DataBase.MyRead.API.DTOs;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Text;

namespace B.S.DataBase.MyRead.API.Appicant.CommandHandler
{
    public class LoginCommandHandler : IRequestHandler<LoginCommand, APIResult<List<LoginDto>>>
    {
        private readonly IBaseRepository<User> userRepos;
        private readonly IBaseRepository<Role> roleRepos;
        private readonly IBaseRepository<RoleUser> roleuserRepos;
        private readonly IMapper mapper;

        public LoginCommandHandler(IBaseRepository<User> userRepos, IBaseRepository<Role> roleRepos, IBaseRepository<RoleUser> roleuserRepos, IMapper mapper)
        {
            this.userRepos = userRepos;
            this.roleRepos = roleRepos;
            this.roleuserRepos = roleuserRepos;
            this.mapper = mapper;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<List<LoginDto>>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {


            APIResult<List<LoginDto>> result = new APIResult<List<LoginDto>>();
            result.Code = APIEnum.登录成功;
            result.Msg = APIEnum.登录成功.ToString();

            var users = userRepos.GetAllAsync().Result;
            var roles = roleRepos.GetAllAsync().Result;
            var roleusers = roleuserRepos.GetAllAsync().Result;
            var link = from a in users
                       join b in roleusers on a.UserId equals b.UserId
                       join c in roles on b.RoleId equals c.RoleId
                       where a.UserName == request.UserName && a.Password == request.Password
                       select new LoginDto
                       {
                           UserId = a.UserId,
                           UserName = a.UserName,
                           NickName = a.NickName,
                           Password = a.Password,
                           RoleId = c.RoleId,
                           DepId=a.DepId,
                           RoleName = c.RoleName,
                           Heads = a.Heads,
                       };
            if (link.Count() < 0 || link == null)
            {
                result.Code = APIEnum.登录失败密码或用户名错误;
                result.Msg = APIEnum.登录失败密码或用户名错误.ToString();
            }

            result.data = link.ToList();
            return await Task.FromResult(result);


        }


        /// <summary>
        /// 生成 JWT Token（令牌）
        /// </summary>
        /// <returns></returns>
        private string CreateTokenString()
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
    }
}
